package com.book.lizhi.ui.fragment;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout.OnRefreshListener;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.android.volley.VolleyError;
import com.book.lizhi.AppApplication;
import com.book.lizhi.AppConfig;
import com.book.lizhi.R;
import com.book.lizhi.adapter.GasStationAdapter;
import com.book.lizhi.constants.Constants;
import com.book.lizhi.http.HttpUtil;
import com.book.lizhi.http.OnHttpAsyncListener;
import com.book.lizhi.model.ArticleModel;
import com.book.lizhi.model.FilmModel;
import com.book.lizhi.model.GasStationModel;
import com.book.lizhi.ui.AboutActivity;
import com.book.lizhi.ui.FilmDetailActivity;
import com.book.lizhi.ui.MyFavActivity;
import com.book.lizhi.ui.UserInfoActivity;
import com.book.lizhi.ui.WebViewActivity;
import com.book.lizhi.util.AppLog;
import com.book.lizhi.util.Util;
import com.book.lizhi.widget.HttpPullRefreshLayout;
import com.book.lizhi.widget.MoreListView;
import com.book.lizhi.widget.MoreListView.OnMoreListener;

public class GasStationFragment extends BaseFragment {
	public static final String CATEGORY = "category";
	private View mView;

	private MoreListView mStoryListView;
	private GasStationAdapter mStoryAdapter;
	private List<GasStationModel> mArticleModels = new ArrayList<GasStationModel>();

	private HttpPullRefreshLayout mAsyncLayout;
	private TextView mTipView;

	private int mPage = 1;

	private String mType;

	public static GasStationFragment newInstance(String category) {
		GasStationFragment fragment = new GasStationFragment();
		Bundle bundle = new Bundle();
		bundle.putString(CATEGORY, category);
		fragment.setArguments(bundle);
		return fragment;
	}

	public GasStationFragment() {
	}

	public GasStationFragment(String type) {
		mType = type;
	}

	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		setHasOptionsMenu(true);
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		AppLog.e("into--[onCreate]:" + mType);

		mView = View.inflate(getActivity(), R.layout.fragment_story, null);
		initUI();

	}

	private void readLocalCache() {
		String lastUrl = Util.getStringBySharePreference(Constants.LAST_REQUEST_GAS_STATION_URL);
		AppLog.e("local", lastUrl == null ? "cache is null!" : lastUrl);
		if (!TextUtils.isEmpty(lastUrl) && !TextUtils.isEmpty(AppApplication.instance.jsonCache.getJsonStr(lastUrl))) {
			mArticleModels.addAll(JSON.parseArray(AppApplication.instance.jsonCache.getJsonStr(lastUrl), GasStationModel.class));
			if (mArticleModels.size() > 0) {
				mAsyncLayout.setDefaultMode(true);
				mStoryAdapter.notifyDataSetChanged();
			}
		} else {
			mAsyncLayout.setDefaultMode(false);
		}
	}

	@Override
	public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
		AppLog.e("into--[onCreateView]:" + mType);
		if (mView.getParent() != null) {
			((ViewGroup) mView.getParent()).removeView(mView);
		}
		return mView;
	}

	@Override
	public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
		Util.setIconEnable(menu, true);
		inflater.inflate(R.menu.setting, menu);
		super.onCreateOptionsMenu(menu, inflater);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		int id = item.getItemId();
		switch (id) {

		case R.id.action_settings:
			startActivity(new Intent(getActivity(), UserInfoActivity.class));
			return true;

		}
		return super.onOptionsItemSelected(item);
	}

	private void initUI() {

		mAsyncLayout = (HttpPullRefreshLayout) findViewById(R.id.library_http_async_layout);
		mAsyncLayout.setColorSchemeResources(R.color.green);

		mTipView = (TextView) findViewById(R.id.tip_view);

		mStoryListView = (MoreListView) findViewById(R.id.book_listView);
		mStoryAdapter = new GasStationAdapter(getActivity(), mArticleModels);
		mStoryListView.setAdapter(mStoryAdapter);

		addListener();
		readLocalCache();
		sendGetRequest(HttpUtil.formateUrl(AppConfig.GAS_STATION_HOST, "0", String.valueOf(System.currentTimeMillis())), mAsyncLayout);
	}

	private List<GasStationModel> parseResponse(String response) {
		JSONObject jsonObject = JSON.parseObject(response);
		List<GasStationModel> articleModels = new ArrayList<GasStationModel>();
		Set<String> keySet = jsonObject.keySet();
		for (String string : keySet) {
			GasStationModel articleModel = JSON.toJavaObject(jsonObject.getJSONObject(string), GasStationModel.class);
			// if (DataBaseMannager.getInstance().isFav(getActivity(), articleModel.id)) {
			// articleModel.isFav = true;
			// }
			articleModels.add(articleModel);
		}
		Util.sortByTime(articleModels);
		return articleModels;
	}

	private void addListener() {
		mAsyncLayout.setOnRefreshListener(new OnRefreshListener() {

			@Override
			public void onRefresh() {
				mAsyncLayout.bringToFront();
				long startTime = 0;
				if (mArticleModels != null && mArticleModels.size() > 0) {
					startTime = Long.parseLong(mArticleModels.get(0).time);
					startTime++;
				}
				sendGetRequest(HttpUtil.formateUrl(AppConfig.GAS_STATION_HOST, String.valueOf(startTime), String.valueOf(System.currentTimeMillis())), mAsyncLayout);

			}
		});
		mAsyncLayout.setOnHttpAsyncListener(new OnHttpAsyncListener() {

			@Override
			public void onHttpSuccess(boolean isCache, String url, String response) {

				List<GasStationModel> tempModels = parseResponse(response);
				if (tempModels.size() > 0) {
					mArticleModels.clear();
					mArticleModels.addAll(tempModels);
					mStoryListView.reset();
					mStoryAdapter.notifyDataSetChanged();
					Util.saveDataBySharePreference(Constants.LAST_REQUEST_GAS_STATION_URL, url);
					AppApplication.instance.jsonCache.saveJsonStr(url, JSON.toJSONString(mArticleModels));
				}
				if (mArticleModels.size() <= 0) {
					// no data;
				}

			}

			@Override
			public void onRefresh() {
				// sendGetRequest(HttpUtil.getArticleListURL(String.valueOf(mPage), mType), mAsyncLayout);
			}

			@Override
			public void onHttpError(VolleyError error) {
				AppLog.e("ERROR", error.toString());
				if (mArticleModels.size() <= 0) {
					mTipView.setText("网络错误!!!\n\n 请稍后下拉试试!");
					mTipView.bringToFront();
				}
			}
		});

		mStoryListView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				Object object = parent.getAdapter().getItem(position);
				if (object instanceof GasStationModel) {
					GasStationModel gasStationModel = (GasStationModel) object;
					Intent intent = new Intent(getActivity(), WebViewActivity.class);
					intent.putExtra(Constants.SOURCE_URL, gasStationModel.detail);
					intent.putExtra(Constants.TITLE, gasStationModel.brief);
					startActivity(intent);
				}
			}
		});
		mStoryListView.setMoreListener(new OnMoreListener() {

			@Override
			public void onMore(boolean isCache, String url, String response) {
				List<GasStationModel> tempModels;
				if (isCache) {
					tempModels = JSON.parseArray(response, GasStationModel.class);
				} else {
					tempModels = parseResponse(response);
					AppApplication.instance.jsonCache.saveJsonStr(url, JSON.toJSONString(tempModels));
				}
				if (tempModels != null && tempModels.size() > 0) {
					mArticleModels.addAll(tempModels);
					mStoryAdapter.notifyDataSetChanged();
				} else {
					mStoryListView.setComplete(true);
				}
			}

			@Override
			public void onLoadMore() {
				long endTime = Long.parseLong(mArticleModels.get(mArticleModels.size() - 1).time);
				endTime--;
				sendGetRequest(HttpUtil.formateUrl(AppConfig.GAS_STATION_HOST, "0", String.valueOf(endTime)), mStoryListView);
			}
		});
	}

	private View findViewById(int resId) {
		return mView.findViewById(resId);
	}

}
